import React, {Component} from 'react'
import {
    Text,
    View,
    StyleSheet,
    Button,
    Image,
    FlatList,
    ScrollView,
    TouchableOpacityComponent,
    TouchableOpacity
} from 'react-native'
import Stepper from "../../component/widget/Stepper";
import {AppIcon} from "../../assets/icon/AppIcon";
import {rectWithSize, default as styles, padding, HUNDRED_PERCENT, margin} from "../../style";
import CommonRadio from "../../component/common/CommonRadio";
import {Actions} from "react-native-router-flux";
import {inject, observer} from "mobx-react/custom";
import {CertStore} from "../../store/modules/cert";
import {Store} from "../../store";
import FastImageCustom from "../../component/widget/FastImageCustom";
import {getAssetUrl, keyExtractor, toFixed} from "../../util";
import CommonFlatList from "../../component/common/CommonFlatList";
import {productOrderItem} from "../primary/checkBill";

interface Order {
    title: string,
    image: any,
    count: number,
    price: number
}

interface CertProps extends Store {

}
type listProp = { item: productOrderItem, index: number };

@inject("cert")
@observer
export default class Cert extends Component<CertProps> {
    cert: CertStore;
    commonList: CommonFlatList;

    constructor(props) {
        super(props);
        this.cert = this.props.cert;
    }

    get hasProducts() {
        return !!this.cert.orderList.length;
    }


    checkBill = () => {
        if (this.hasProducts) {
            Actions.push("CheckBill", {orderList: this.cert.orderList})
        }
    };

    _renderBottomBar() {
        return (<View style={[CertStyles.row, CertStyles.bottomBar, styles.justifyEnd]}>
            <View style={[styles.flexDirectionRowNotFlex]}>
                <Text style={{color: "#333333", fontSize: 14}}>合计：</Text>
                <Text style={{color: "#DB0000", fontSize: 14}}>￥{toFixed(this.totalPrice())}</Text>
            </View>
            <TouchableOpacity onPress={this.checkBill} style={[styles.centered, padding(7, 44), {
                borderRadius: 3,
                marginLeft: 14,
                backgroundColor: this.hasProducts ? "#629C36" : "#ccc"
            }]}>
                <Text style={{fontSize: 16, color: "#FFFFFF"}}>结算</Text>
            </TouchableOpacity>
        </View>)
    }

    removeOrderProductItem(item: productOrderItem) {
        return () => this.cert.removeOrderItem(item);
    };

    totalPrice() {
        if (!this.cert.orderList.length) return 0;
        return this.cert.orderList.reduce((initVal: number, cur: productOrderItem) => {
            const curPrice = cur.product.price * cur.count;
            return initVal + curPrice;
        }, 0);
    }

    computedProductPrice(productItem) {
        const {selectedSpecification, product} = productItem;
        return selectedSpecification.id ? selectedSpecification.price : product.price;
    }

    updateOrderItemCount = (itemIndex: number) => {
        return (count: number) => {
            const orderList = this.cert.orderList;
            this.cert.updateOrderItemCount(orderList[itemIndex], count);
        }
    };

    _renderList = ({item, index}:listProp) => {
        const {product, selectedSpecification, count,maxCount} = item;
        const {name, imageUrl, infoImageUrl} = product;
        const price = this.computedProductPrice(item);
        const {name: sepcName} = selectedSpecification;
        return (
            <View style={[CertStyles.row, padding(10, 18), {height: 90}]}>
                <CommonRadio size={16} checked={true}/>
                <FastImageCustom source={{uri: getAssetUrl(infoImageUrl)}} resizeMode={"contain"}
                                 style={[rectWithSize(60), {marginLeft: 11}]}/>
                <View style={[styles.justifyBetween, styles.flex, {
                    height: HUNDRED_PERCENT,
                    marginHorizontal: 10
                }]}>
                    <View>
                        <Text style={CertStyles.commonFont} numberOfLines={2}>{name}</Text>
                        <Text style={{fontSize: 12, color: "#999999", marginBottom: 8}}
                              numberOfLines={1}>{sepcName}</Text>
                    </View>
                    <Stepper maxCount={maxCount} updateCount={this.updateOrderItemCount(index)} textStyle={{fontSize: 12}}
                             style={{marginTop: 3}} count={count}/>
                </View>
                <View style={[styles.justifyBetween, styles.centerH, {height: HUNDRED_PERCENT}]}>
                    <Text style={CertStyles.commonFont}>￥{price * count}</Text>
                    <TouchableOpacity onPress={this.removeOrderProductItem(item)}>
                        <AppIcon name={"lajitong"} size={18} color={"#999999"}/>
                    </TouchableOpacity>
                </View>
            </View>)
    }

    _refresh = () => {
        setTimeout(() => {
            this.commonList.refreshComplete(false);
        }, 1000);
    };
    _loadMore = () => {

    };


    _renderHeader() {
        return (
            <View>
                <View style={[CertStyles.row, {height: 40}]}>
                    <CommonRadio size={16} checked={true}/>
                    <Text style={{fontSize: 14, color: "#333333", marginLeft: 11}}>全部</Text>
                </View>
            </View>
        )
    }

    render() {
        return (
            <View style={styles.flex}>
                <CommonFlatList ref={commonList => this.commonList = commonList}
                                ListHeaderComponent={this._renderHeader()} keyExtractor={keyExtractor}
                                data={this.cert.orderList}
                                renderItem={this._renderList}
                                loadMore={this._loadMore}
                                refresh={this._refresh} style={CertStyles.container}>
                </CommonFlatList>
                {this._renderBottomBar()}
            </View>
        )
    }
}

const style: any = {
    commonFont: {
        fontSize: 12,
        color: "#333333"
    },
    row: {
        backgroundColor: "#fff",
        marginTop: 1,
        paddingHorizontal: 18,
        flexDirection: "row",
        alignItems: "center",
    },
    bottomBar: {
        height: 50,
        position: "absolute",
        bottom: 0,
        left: 0,
        right: 0
    }
};

const CertStyles = StyleSheet.create({
    ...style,
    container: {
        flex: 1,
        position: "relative"
    }
});
